package com.system.honour.service.impl;

import com.system.honour.beans.PageQuery;
import com.system.honour.beans.PageResult;
import com.system.honour.common.ResultDTO;
import com.system.honour.dto.UserDTO;
import com.system.honour.entity.SysRoleUser;
import com.system.honour.entity.SysUser;
import com.system.honour.exception.CustomizeErrorCode;
import com.system.honour.mapper.SysRoleUserMapper;
import com.system.honour.mapper.SysUserMapper;
import com.system.honour.service.UserService;
import com.system.honour.util.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysRoleUserMapper roleUserMapper;

    @Override
    public SysUser getUser(String username) {
        return userMapper.getUser(username);
    }

    @Override
    public PageResult<SysUser> getUserByPage(PageQuery page) {
        Integer count = userMapper.countAllUser();
        List<SysUser> users = null;
        if (count>0){
            users = userMapper.getUserByPage(page);
            return PageResult.<SysUser>builder().data(users).total(count).build();
        }
        return PageResult.<SysUser>builder().build();
    }

    @Override
    public ResultDTO save(UserDTO param, Integer roleId) {
        if (checkTelephoneExist(param.getTelephone(),param.getId())){
            return ResultDTO.errorOf(CustomizeErrorCode.TELEPHONE_HAS);
        }
        if (roleId!=null){
            //1.user save
            // TODO 验证重复创建
            //检查是否有密码传入，没有即设置默认密码
            String password = param.getPassword();
            String defaultPass = "123456";
            if (password==null){
                password=defaultPass;
            }
            String newPass = new BCryptPasswordEncoder().encode(password);

            SysUser user = SysUser.builder()
                    .username(param.getUsername())
                    .telephone(param.getTelephone())
                    .email(param.getEmail())
                    .password(newPass)
                    .remark(param.getRemark())
                    .deptId(param.getDeptId())
                    .status(param.getStatus())
                    .nickname(param.getNickname())
                    .phone(param.getPhone())
                    .birthday(param.getBirthday())
                    .sex(param.getSex())
                    .herdImgUrl(param.getHerdImgUrl()).build();
            user.setOperatorTime(new Date());
            userMapper.insertSelective(user);

            //2 user-role save
            SysRoleUser roleUser = new SysRoleUser();
            roleUser.setRoleId(roleId);
            roleUser.setUserId(user.getId());
            roleUserMapper.insertSelective(roleUser);
            return ResultDTO.okOf(user);
        }
        return ResultDTO.errorOf(CustomizeErrorCode.NO_ROLE_ID);


    }

    @Override
    public ResultDTO update(UserDTO param, Integer roleId) {

        //检查是否有密码传入，没有即不修改
        String password = param.getPassword();
        String newPass = null;
        if (password!=null){
            newPass= new BCryptPasswordEncoder().encode(password);
        }

        SysUser user = SysUser.builder()
                .id(param.getId())
                .username(param.getUsername())
                .telephone(param.getTelephone())
                .email(param.getEmail())
                .password(newPass)
                .remark(param.getRemark())
                .deptId(param.getDeptId())
                .status(param.getStatus())
                .nickname(param.getNickname())
                .phone(param.getPhone())
                .birthday(param.getBirthday())
                .sex(param.getSex())
                .herdImgUrl(param.getHerdImgUrl()).build();
        user.setOperatorTime(new Date());
        userMapper.updateByPrimaryKeySelective(user);

        //2 user-role  update save
        //是否已经存在：存在不做处理，不存在进行保存
        SysRoleUser roleUser = new SysRoleUser();
        roleUser.setRoleId(roleId);
        roleUser.setUserId(user.getId());
        List<SysRoleUser> roleUserList = roleUserMapper.getByUserId(user.getId());
        if(roleUserList!=null&&roleUserList.size()>0){
            roleUserMapper.updateByUserId(roleUser);
        }else {
            roleUserMapper.insertSelective(roleUser);
        }

        return ResultDTO.okOf();
    }

    @Override
    public SysUser getByTelephone(String telephone) {
        return userMapper.getByTelephone(telephone);
    }

    @Override
    public ResultDTO deleteById(Integer id) {
        SysUser user = userMapper.selectByPrimaryKey(id);
        if (user!=null){
            List<SysRoleUser> roleUserList = roleUserMapper.getByUserId(user.getId());
            if (roleUserList!=null&& roleUserList.size()>0){
                roleUserMapper.deleteByUserId(user.getId());
            }
            userMapper.deleteByPrimaryKey(id);
            return ResultDTO.okOf();
        }
        return ResultDTO.errorOf(CustomizeErrorCode.INCORRECT_INFORMATION);
    }

    @Override
    public PageResult getUserByVague(String username, PageQuery page) {
        Integer count = userMapper.countByVague(username);
        List<SysUser> userList = null;
        if (count>0){
            userList=userMapper.getUserByVague(page,username);
            return PageResult.<SysUser>builder().data(userList).total(count).build();
        }
        return PageResult.<SysUser>builder().build();
    }

    /**
     * 电话是否存在
     * @param Telephone
     * @param userId
     * @return
     */
    private boolean checkTelephoneExist(String Telephone, Integer userId){
        return userMapper.countByTelephone(Telephone,userId)>0;
    }
}
